<template>
  <div class="detail-tabs-container">
    <el-tabs v-model="activeTab" class="detail-tabs">
      <el-tab-pane label="题目列表" name="problems">
        <template #label>
          <el-icon class="tab-icon"><Document /></el-icon>
          <span>题目列表</span>
        </template>
        <div class="tab-content">
          <ProblemListTab :problemSet="problemSet" @refresh="handleRefresh" />
        </div>
      </el-tab-pane>

      <el-tab-pane label="成员列表" name="members">
        <template #label>
          <el-icon class="tab-icon"><User /></el-icon>
          <span>成员列表</span>
        </template>
        <div class="tab-content">
          <MemberListTab :setId="problemSet.id" :userRole="problemSet.userRole" />
        </div>
      </el-tab-pane>

      <el-tab-pane label="提交记录" name="submissions">
        <template #label>
          <el-icon class="tab-icon"><List /></el-icon>
          <span>提交记录</span>
        </template>
        <div class="tab-content">
          <SubmissionListTab />
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { computed, defineAsyncComponent, h, onMounted, ref } from "vue"
import { useRouter } from "vue-router"
import { ElButton, ElIcon, ElMessage } from "element-plus"
import { Document, List, Plus, User, VideoPlay } from "@element-plus/icons-vue"

const props = defineProps({
  problemSet: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(["refresh"])

const activeTab = ref("problems")

// 处理刷新事件
const handleRefresh = () => {
  emit("refresh")
}

// 题目列表组件
const ProblemListTab = {
  props: {
    problemSet: {
      type: Object,
      required: true
    }
  },
  emits: ["refresh"],
  setup(props, { emit }) {
    const router = useRouter()
    const problems = computed(() => props.problemSet?.problems || [])
    const isCreator = computed(() => props.problemSet?.userRole === "CREATOR")
    const selectorDialogVisible = ref(false)

    // 打开题目选择器
    const openProblemSelector = () => {
      selectorDialogVisible.value = true
    }

    // 添加成功后刷新
    const handleAddSuccess = () => {
      ElMessage.success("题目添加成功")
      emit("refresh")
    }

    // 开始解题
    const handleStartSolve = problemId => {
      // 跳转到解题页面，并传递题目集ID
      router.push(`/problem/solve/${problemId}?setId=${props.problemSet.id}`)
    }

    return () => {
      const headerSection = h("div", { class: "problem-list-header" }, [
        h("div", { class: "header-title" }, `题目列表 (${problems.value.length})`),
        isCreator.value
          ? h(
              ElButton,
              {
                type: "primary",
                onClick: openProblemSelector
              },
              {
                default: () => [h(ElIcon, null, { default: () => h(Plus) }), h("span", " 添加题目")]
              }
            )
          : null
      ])

      let contentSection
      if (!problems.value || problems.value.length === 0) {
        contentSection = h("div", { class: "empty-state" }, [
          h("div", { style: "font-size: 16px; color: #909399; margin-bottom: 12px;" }, "暂无题目"),
          isCreator.value
            ? h(
                ElButton,
                {
                  type: "primary",
                  onClick: openProblemSelector
                },
                {
                  default: () => "添加题目"
                }
              )
            : null
        ])
      } else {
        contentSection = problems.value.map((problem, index) =>
          h("div", { class: "list-item", key: problem.id }, [
            h("div", { class: "item-index" }, index + 1),
            h("div", { class: "item-content" }, [
              h("div", { class: "item-title" }, problem.problemTitle || `题目 ${problem.problemId}`),
              h("div", { class: "item-meta" }, [
                problem.problemDifficulty ? h("span", { class: "meta-tag difficulty" }, problem.problemDifficulty) : null,
                problem.problemCategory ? h("span", { class: "meta-tag category" }, problem.problemCategory) : null,
                problem.targetScore ? h("span", { class: "meta-info" }, `目标分数: ${problem.targetScore}`) : null
              ])
            ]),
            h("div", { class: "item-actions" }, [
              h(
                ElButton,
                {
                  type: "primary",
                  onClick: () => handleStartSolve(problem.problemId)
                },
                {
                  default: () => [h(ElIcon, null, { default: () => h(VideoPlay) }), h("span", " 开始解题")]
                }
              )
            ])
          ])
        )
      }

      // 动态导入题目选择器组件
      const ProblemSelectorDialog = selectorDialogVisible.value
        ? h(
            defineAsyncComponent(() => import("./problemSelectorDialog.vue")),
            {
              visible: selectorDialogVisible.value,
              "onUpdate:visible": val => {
                selectorDialogVisible.value = val
              },
              setId: props.problemSet?.id,
              existingProblems: problems.value,
              onSuccess: handleAddSuccess
            }
          )
        : null

      return h("div", { class: "tab-list-container" }, [headerSection, contentSection, ProblemSelectorDialog])
    }
  }
}

// 成员列表组件
const MemberListTab = {
  props: {
    setId: {
      type: Number,
      required: true
    },
    userRole: String
  },
  setup(props) {
    const members = ref([])
    const loading = ref(false)
    const total = ref(0)
    const pageNum = ref(1)
    const pageSize = ref(10)

    const loadMembers = async () => {
      if (!props.setId) return
      loading.value = true
      try {
        const { getProblemSetMembers } = await import("@/api/modules/problem-set")
        const result = await getProblemSetMembers(props.setId, {
          pageNum: pageNum.value,
          pageSize: pageSize.value
        })

        if (result.code === 200) {
          members.value = result.data.records || []
          total.value = result.data.total || 0
        }
      } catch (error) {
        console.error("加载成员列表失败:", error)
        ElMessage.error("加载成员列表失败")
      } finally {
        loading.value = false
      }
    }

    const handlePageChange = page => {
      pageNum.value = page
      loadMembers()
    }

    const getRoleName = role => {
      const roleMap = {
        CREATOR: "创建者",
        MEMBER: "成员"
      }
      return roleMap[role] || role
    }

    const getRoleClass = role => {
      return role === "CREATOR" ? "role-creator" : "role-member"
    }

    const formatJoinTime = time => {
      if (!time) return ""
      const d = new Date(time)
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`
    }

    onMounted(() => {
      loadMembers()
    })

    return () => {
      if (loading.value) {
        return h("div", { class: "tab-list-container loading" }, [h("div", { class: "loading-text" }, "加载中...")])
      }

      if (!members.value || members.value.length === 0) {
        return h("div", { class: "tab-list-container" }, [h("div", { class: "empty-state" }, [h("div", { style: "font-size: 16px; color: #909399;" }, "暂无成员")])])
      }

      const listItems = members.value.map((member, index) =>
        h("div", { class: "list-item", key: member.userId }, [
          h("div", { class: "item-index" }, index + 1),
          h("div", { class: "item-content" }, [
            h("div", { class: "item-title" }, member.userName),
            h("div", { class: "item-meta" }, [
              h("span", { class: `meta-tag ${getRoleClass(member.role)}` }, getRoleName(member.role)),
              h("span", { class: "meta-info" }, member.userEmail),
              h("span", { class: "meta-info" }, `加入时间：${formatJoinTime(member.joinedAt)}`)
            ])
          ])
        ])
      )

      const pagination =
        total.value > pageSize.value
          ? h("div", { class: "pagination-wrapper" }, [
              h("div", { class: "pagination-info" }, `共 ${total.value} 条`),
              h("div", { class: "pagination-controls" }, [
                h(
                  "button",
                  {
                    class: "pagination-btn",
                    disabled: pageNum.value === 1,
                    onClick: () => handlePageChange(pageNum.value - 1)
                  },
                  "上一页"
                ),
                h("span", { class: "pagination-current" }, `${pageNum.value} / ${Math.ceil(total.value / pageSize.value)}`),
                h(
                  "button",
                  {
                    class: "pagination-btn",
                    disabled: pageNum.value >= Math.ceil(total.value / pageSize.value),
                    onClick: () => handlePageChange(pageNum.value + 1)
                  },
                  "下一页"
                )
              ])
            ])
          : null

      return h("div", { class: "tab-list-container" }, [...listItems, pagination])
    }
  }
}

// 提交记录组件
const SubmissionListTab = {
  setup() {
    return () => {
      return h("div", { class: "tab-list-container" }, [
        h("div", { class: "empty-state" }, [
          h("div", { style: "font-size: 16px; color: #909399; margin-bottom: 8px;" }, "提交记录功能开发中"),
          h("div", { style: "font-size: 14px; color: #c0c4cc;" }, "敬请期待")
        ])
      ])
    }
  }
}
</script>

<style lang="scss" scoped>
@use "@/styles/base/variables" as *;
@use "@/styles/base/mixins" as *;

.detail-tabs-container {
  background: var(--color-bg-primary);
  border-radius: $border-radius-lg;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--color-border-secondary);
  overflow: hidden;
  @include theme-transition;

  :deep(.el-tabs__header) {
    margin: 0;
    padding: 0 20px;
    background: var(--color-bg-secondary);
    border-bottom: 2px solid var(--color-border-tertiary);
  }

  :deep(.el-tabs__nav-wrap::after) {
    display: none;
  }

  :deep(.el-tabs__item) {
    font-size: 15px;
    font-weight: 600;
    padding: 16px 20px;
    color: var(--color-text-secondary);
    transition: color $transition-fast;

    &:hover {
      color: var(--color-primary);
    }

    &.is-active {
      color: var(--color-primary);
    }
  }

  :deep(.el-tabs__active-bar) {
    height: 3px;
    background: var(--color-primary);
  }

  .tab-icon {
    margin-right: 6px;
    font-size: 16px;
  }

  .tab-content {
    padding: 20px;
    min-height: 400px;
  }

  // 统一的列表容器样式
  :deep(.tab-list-container) {
    .problem-list-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      padding-bottom: 12px;
      border-bottom: 1px solid var(--color-border-tertiary);

      .header-title {
        font-size: 16px;
        font-weight: 600;
        color: var(--color-text-primary);
      }
    }

    .list-item {
      display: flex;
      align-items: center;
      padding: 16px 20px;
      background: var(--color-bg-secondary);
      border-radius: $border-radius-base;
      border: 1px solid var(--color-border-secondary);
      margin-bottom: 12px;
      transition: all $transition-fast;

      &:hover {
        background: var(--color-bg-tertiary);
        border-color: var(--color-primary-light-7);
        transform: translateX(4px);
      }

      .item-index {
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: var(--color-primary-light-9);
        color: var(--color-primary);
        border-radius: 50%;
        font-weight: 700;
        font-size: 16px;
        flex-shrink: 0;
        margin-right: 16px;
      }

      .item-content {
        flex: 1;
        min-width: 0;

        .item-title {
          font-size: 15px;
          font-weight: 600;
          color: var(--color-text-primary);
          margin-bottom: 8px;
        }

        .item-meta {
          display: flex;
          align-items: center;
          gap: 12px;
          flex-wrap: wrap;

          .meta-tag {
            padding: 2px 8px;
            border-radius: $border-radius-sm;
            font-size: 12px;
            font-weight: 500;

            &.difficulty {
              background: var(--color-warning-light-9);
              color: var(--color-warning);
            }

            &.category {
              background: var(--color-info-light-9);
              color: var(--color-info);
            }

            &.role-creator {
              background: var(--color-success-light-9);
              color: var(--color-success);
            }

            &.role-member {
              background: var(--color-info-light-9);
              color: var(--color-info);
            }
          }

          .meta-info {
            font-size: 13px;
            color: var(--color-text-tertiary);
          }
        }
      }

      .item-actions {
        flex-shrink: 0;
        margin-left: 16px;
      }
    }

    .empty-state {
      padding: 60px 20px;
      text-align: center;
      color: var(--color-text-tertiary);
    }

    .loading-text {
      padding: 40px;
      text-align: center;
      color: var(--color-text-tertiary);
      font-size: 14px;
    }

    .pagination-wrapper {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px;
      margin-top: 8px;
      background: var(--color-bg-secondary);
      border-radius: $border-radius-base;

      .pagination-info {
        font-size: 14px;
        color: var(--color-text-secondary);
      }

      .pagination-controls {
        display: flex;
        align-items: center;
        gap: 12px;

        .pagination-btn {
          padding: 6px 12px;
          border: 1px solid var(--color-border-secondary);
          background: white;
          border-radius: $border-radius-sm;
          font-size: 14px;
          cursor: pointer;
          transition: all $transition-fast;

          &:hover:not(:disabled) {
            border-color: var(--color-primary);
            color: var(--color-primary);
          }

          &:disabled {
            opacity: 0.5;
            cursor: not-allowed;
          }
        }

        .pagination-current {
          font-size: 14px;
          color: var(--color-text-secondary);
          padding: 0 8px;
        }
      }
    }
  }
}
</style>
